package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;

/**
 * @Author LEO
 * @Date 2021年12月10日 9:42
 */
@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //select * from base_category2 where category1_id  = category1Id
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id",category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //select * from base_category2 where category2_id  = category2Id
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id));
    }



    @Override
    public List<BaseAttrInfo> getBaseAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //根据分类id查询平台属性列表
        // 后续有可能需要查询平台 属性+平台属性，因此这个方法中，一次将所有数据全部查询即可

        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id, category2Id, category3Id);
    }

    /**
     * 保存平台属性方法
     * @param baseAttrInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)    // 如果出现异常则回滚，代码块出现非运行异常，照样回滚
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //  DML 语句 插入数据 需要注意事务
        //判断 baseAttrInfo.id是否为空
        //更新
        if (baseAttrInfo.getId()!=null){
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }else {
            //新增
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
            // int i= 1/0;

        //什么时候新增，什么时候修改
        //不知道什么时候,先删除，再增加
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId());
        // delete from base_attr_value where attr_id = baseAttrInfo.getId()
        baseAttrValueMapper.delete(queryWrapper);

        //先获取平台属性值集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();

        //不为空
        if (!CollectionUtils.isEmpty(attrValueList)){
            //遍历当前集合，插入到平台属性表中
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //attr_id 这个字段需要处理,  表字段 base_attr_id.id = base_attr_value.attr_id
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }

    //根据平台属性ID获取平台属性对象数据
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id",attrId));
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        if (baseAttrInfo != null){
            //获取平台属性集合对象数据
            List<BaseAttrValue> attrValueList = getAttrValueList(attrId);
            if (!CollectionUtils.isEmpty(attrValueList)){
                baseAttrInfo.setAttrValueList(attrValueList);
            }
//    test
        }
        return baseAttrInfo;
    }

    /**
     *  根据三级分类ID 获取spuInfo 集合数据
     * @param spuInfoPage
     * @param spuInfo
     * @return
     */
    @Override
    public IPage<SpuInfo> getSpuInfoList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        queryWrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(spuInfoPage,queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        /** 表名
         * 1.spu_info
         * 2.spu_image
         * 3.spu_sle_attr
         * 4.spu_sale_attr_value
         */

        spuInfoMapper.insert(spuInfo);
        //先获取spuImageList 集合
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            for (SpuImage spuImage : spuImageList) {
                //将psuId赋值
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }
        //获取当前的销售属性集合
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }
    }


    /**
     * 查询所有的销售属性数据
     * @return
     */
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }


    //select * from spu_image where spu_id = spuId
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        QueryWrapper<SpuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        List<SpuImage> spuImages = spuImageMapper.selectList(queryWrapper);
        return spuImages;
    }


    //回显销售属性+销售属性值！
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrList= spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }

    //保存skuInfo！
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /**
         * 1.sku_info
         * 2.sku_attr_value
         * 3.sku_sale_attr_value
         * 4.sku_image
         */
        skuInfoMapper.insert(skuInfo);
        //获取sku_attr_value表对应数据
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
                // 赋值skuId
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }
        // 获取sku_sale_attr_value表对应数据
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                //赋值spuId, skuId,
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }

        //获取sku_image表对应数据
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if(!CollectionUtils.isEmpty(skuImageList)){
            for (SkuImage skuImage : skuImageList) {
                //赋值skuId
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }
    }

    //查询skuInfo 列表，
    @Override
    public IPage getSkuInfoList(Page<SkuInfo> skuInfoPage) {
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage,queryWrapper);
    }


    @Autowired
    private RabbitService rabbitService;

    //商品的上架 上架:{is_sale = 1}
    //	http://api.gmall.com/admin/product/onSale/{skuId}
    //		update  sku_info set is_sale = 1 where id = 45;
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
         skuInfoMapper.updateById(skuInfo);
         // 发送消息mq
        // 消息主体：由消费者决定 upperGoods(Long skuId)   skuId决定
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    //商品的下架 下架: {is_sale = 0}
    //		http://api.gmall.com/admin/product/cancelSale/{skuId}
    //		update  sku_info set is_sale = 0 where id = 45;
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
        // 发送消息mq
        // 消息主体：由消费者决定 upperGoods(Long skuId)   skuId决定
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }


    /**
     *  根据skuId 查询skuInfo 以及skuImageList
     * @param skuId
     * @return
     */
    @Override
    // 加个注解就能代替 分布式锁的业务逻辑
    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {
//        SkuInfo skuInfo = new SkuInfo();
//
//        // 如果redis宕机了就废了 redisTemplate.opsForValue().get(skuKey);
//        try {
//            // * 获取缓存数据  如何获取数据
////        redisTemplate.opsForHash() 能 hset(key,field,value)  field=实体类属性名   便于修改，hget(field,value)
//            // 商品详情页  string存储
//            //skuKey =sku:skuId:info
//            String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
//            //因为配置类中已经将String ,hash 做了序列化  com.atguigu.gmall.common.config.RedisConfig 配置类
//            skuInfo= (SkuInfo) redisTemplate.opsForValue().get(skuKey);
//
//            //防止缓存击穿
//            if(skuInfo==null){
//                //走数据库 --->给缓存
//                //上锁
//                //定义一个锁的key=sku:skuId:lock
//               String skuLockKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
//               String uuid= UUID.randomUUID().toString();
//               // 开始上锁
//               boolean flag=  redisTemplate.opsForValue().setIfAbsent(skuLockKey,uuid,RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
//                if (flag){
//                    // 上锁成功
//                    // 要查询数据库，防止缓存穿透
//                     skuInfo= getSkuInfoDB(skuId);
//                     if(skuInfo==null){
//                         //放入一个空对象
//                         SkuInfo skuInfo1=  new SkuInfo();
//                         redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
//                         return skuInfo;
//                     }
//                     // 将数据放入缓存,并返回
//                    redisTemplate.opsForValue().set(skuId,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
//                     //释放锁  使用lua脚本
//                    String script="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
//                    redisScript.setScriptText(script);
//                    redisTemplate.execute(redisScript, Arrays.asList(skuLockKey),uuid);  //锁的key 和值
//                    //返回数据
//                    return skuInfo;
//                }
//
//            }else {
//                //说明缓存中有数据
//                return skuInfo;
//            }
//        } catch (Exception e) {
//            // sout("redis宕机了")
//            //调用发短信之类
//            e.printStackTrace();
//        }

        // 调用redisson
        //数据库兜底 有风险
        return getSkuInfoDB(skuId);
    }

    //根据skuId 查询数据库
    private SkuInfo getSkuInfoDB(Long skuId){
        // select * from sku_info where id=skuId
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        //select * from sku_image where skuId=skuId
        QueryWrapper<SkuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id",skuId);
        List<SkuImage> skuImageList = skuImageMapper.selectList(queryWrapper);
        // 将skuImageList集合赋值给skuInfo对象
        skuInfo.setSkuImageList(skuImageList);
        return skuInfo;
    }



    /**
     * 通过三级分类id查询分类信息
     * @param category3Id
     * @return
     */
    @Override
    @GmallCache(prefix = "categoryViewByCategory3Id:")
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        //select * from base_category_view where id=category3Id
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     * 根据skuId获取商品价格
     * @param skuId
     * @return
     */
    @Override
    @GmallCache(prefix = "skuPrice:")
    public BigDecimal getSkuPrice(Long skuId) {
        //select price from sku_info where id=skuId;
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null){
            BigDecimal price = skuInfo.getPrice();
            return price;
        }
        //默认值
        return new BigDecimal(0);
    }


    // 根据spuId，skuId 查询销售属性集合
    @Override
    @GmallCache(prefix = "spuSaleAttrListCheckBySku:")
    public List<SpuSaleAttr> selectSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    /**
     * 根据spuId 获取销售属性值id 与skuId 的组合数据
     * @param spuId
     * @return
     */
    @Override
    @GmallCache(prefix = "skuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        Map map = new HashMap<>();
        //执行sql 获取数据结果集
       List<Map> mapList = skuSaleAttrValueMapper.selectSaleAttrValuesBySpu(spuId);
       if (!CollectionUtils.isEmpty(mapList)){
           for (Map maps : mapList) {
               //循环获取到的数据放入map
               // 通过Map转换成Json {"126|124":"46"，"126|125":"47"}   skuId=46 valueIds=124|126
               map.put(maps.get("value_ids"),maps.get("sku_id"));
           }
       }
        return map;
    }

    @Override
    public List<JSONObject> getBaseCategoryList() {
        List<JSONObject> list = new ArrayList<>();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("index",1);
        //查询所有分类数据  select * from base_category_view
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        //声明一个index
        int index=1;

        //按照一级分类ID进行分组
        // key =category1Id value=List<BaseCategoryView
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        // 循环遍历当前的集合数据
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = category1Map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            //获取对应的key value
            Long category1Id = entry.getKey();
            List<BaseCategoryView> category2List = entry.getValue();
            // 获取一级分类名称
            String categoryName=category2List.get(0).getCategory1Name();
            //赋值
            JSONObject category1 = new JSONObject();
            category1.put("index",index);
            category1.put("categoryName",categoryName);
            category1.put("categoryId",category1Id);

            //index 迭代
            index++;

            //获取二级分类数据
            Map<Long, List<BaseCategoryView>> category2Map = category2List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            // 声明一个二级分类集合数据
            List<JSONObject> category2Child=new ArrayList<>();
            //循环遍历
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = category2Map.entrySet().iterator();
            while (iterator1.hasNext()){
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                // 获取key value
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> category3List = entry1.getValue();

                String category2Name=category3List.get(0).getCategory2Name();
                //赋值
                JSONObject category2 = new JSONObject();
                category2.put("index",index);
                category2.put("categoryName",category2Name);
                category2.put("categoryId",category2Id);

                category2Child.add(category2);


                // 声明一个三级分类集合数据
                List<JSONObject> category3Child=new ArrayList<>();
                // 三级分类数据
                category3List.forEach(baseCategoryView -> {
                    JSONObject category3 =  new JSONObject();
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3Child.add(category3);
                });
                //将三级分类数据放入二级对象
                category2.put("categoryChild",category3Child);
            }
            // 将二级分类数据放入一级对象
            category1.put("categoryChild",category2Child);

            // 将一级分类数据放入list中
            list.add(category1);
        }


        // 返回结果集
        return list;
    }


    @Autowired
    private BaseTrademarkMappper baseTrademarkMappper;

    /**
     * 通过品牌Id 来查询数据
     * @param tmId
     * @return
     */
    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
       return baseTrademarkMappper.selectById(tmId);
    }


    /**
     * 通过skuId 集合来查询属性和属性值数据
     * @param skuId
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }


}
